const computedWords = (json: any[] = []) => {
    let count = 0;
    json.forEach(row => {
        if(row.data) {
            if(row.data.text) {
                count+= row.data.text.length;
                return
            }
            if(row.data.message) {
                count+= row.data.message.length;
                return
            }
            if(row.data.items && row.data.items.length) {
                row.data.items.forEach((v: any) => {
                    count+= typeof v === 'string' ? v.length : (v.text || v.content).length;
                })
                return
            }
            count++;
        }
    })
    return count
}

const formatUsedTime = (seconds: number = 0) => {
    const _secs = Math.ceil(seconds);
    if(_secs < 60) {
        return `${_secs} 秒`
    }
    const mins = Math.floor(_secs / 60);
    if(mins < 60) {
        const rest = _secs % 60;
        return `${mins} 分 ${rest} 秒`
    }
    return `${Math.ceil(mins / 60)}小时`
}

function debounce(fn: Function, time: number) {
    let timer: any;
    return function (this: object, ...args: any[]) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, args);
        clearTimeout(timer);
      }, time);
    }
  }

  function throttleRAF(fn: Function) {
    let running = false;
    return function () {
        if(running) return
        running = true;
        window.requestAnimationFrame((timestemp) => {
            fn();
            running = false;
        })
    }
  }

export {
    computedWords,
    throttleRAF,
    debounce,
    formatUsedTime
}